import axios from 'axios'
import qs from 'qs'
// import store from '@/store'
import { getToken } from '@utils/auth'
import { config } from './api.config'
import { Toast } from 'vant'

// create an axios instance
const service = axios.create(config)

// request interceptor 添加请求拦截器
service.interceptors.request.use(
  config => {
    // 在发送请求之前做些什么
    const { token, userId } = getToken()

    config.headers = { ...config.headers, token, userId }

    if (config.method === 'post') config.data = qs.stringify(config.data)

    return config
  },
  error => {
    // 对请求错误做些什么
    console.log('requestError', error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor 添加响应拦截器
service.interceptors.response.use(
  response => {
    // 对响应数据做点什么
    const { status, data } = response
    if (status === 200) {
      const { resultCode, resultMsg } = data
      if (resultCode === '00100000') {
        return data
      } else {
        Toast(resultMsg)
        return Promise.reject(response)
      }
    } else {
      return Promise.reject(response)
    }
  },
  error => {
    // 对响应错误做点什么
    console.log('responseError', error) // for debug
    return Promise.reject(error)
  }
)

export default service
